﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ResourceTypeConfigurationApp
{
    public partial class fmNewSite : Form
    {
        public fmNewSite()
        {
            InitializeComponent();
        }

        private async void btnNew_Click(object sender, EventArgs e)
        {
            DataTable dtA = bindingSource1.DataSource as DataTable;


            if (dtA == null || !dtA.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
            {
                MessageBox.Show("请先勾选数据");
                return;
            }


            var row = dtA.AsEnumerable().FirstOrDefault(x => x["IsSelected"].ToString() == "True");
            //先查询站点是否已经有这个数据
            var dtSite = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,site_name,pkey FROM site_15min WHERE pkey ={MySQLHelper.ConvertGuidToSql(row["ID"].ToString())}");
            if (dtSite.Rows.Count > 0)
            {
                MessageBox.Show($@"站点{row["NAME"]}已存在");
                return;
            }
            //插入数据
            string strSql = $@"INSERT INTO site_15min (site_name,pkey,parent_pkey,create_time) VALUES ({MySQLHelper.ConvertGuidToSql(row["NAME"].ToString())},{MySQLHelper.ConvertGuidToSql(row["ID"].ToString())},{MySQLHelper.ConvertGuidToSql(txtParentID.Text)},NOW())";

            if (await MySQLHelper.ExecuteSql(MySQLHelper.targetConnectionString, strSql))
            {
                MessageBox.Show("新建站点成功");
            }
            else
            {
                MessageBox.Show("新建站点失败");
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                MessageBox.Show("请输入企业名称");
                return;
            }
            txtPath.Text = "";

            var dtA =await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.soureConnectionString, $@"SELECT ID,CLASSNAME,`NAME`,PATHID FROM dev_powersystemresource WHERE `NAME` LIKE '%{txtName.Text}%' AND CLASSNAME IN( 'FactoryStation','Filiale' ) order by PATHID");
            if (dtA.Rows.Count == 0)
            {
                MessageBox.Show("没有查询到相关数据");
                return;
            }
            dgSite.Columns.Clear();
            // 创建一个DataGridViewCheckBoxColumn
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.HeaderText = "选中";
            checkBoxColumn.Name = "IsSelected";
            checkBoxColumn.DataPropertyName = "IsSelected";
            // 将勾选列添加到DataGridView
            dgSite.Columns.Add(checkBoxColumn);

            // 为DataTable添加对应的列
            dtA.Columns.Add("IsSelected", typeof(bool));
            dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

            // 设置不允许新增行
            dgSite.AllowUserToAddRows = false;
            dgSite.AllowUserToDeleteRows = false; // 禁止删除行

            bindingSource1.DataSource = dtA;
            dgSite.DataSource = bindingSource1;

            //dataGridView1.DataSource = dtA;
            dgSite.Columns["ID"].HeaderText = "ID";
            dgSite.Columns["CLASSNAME"].HeaderText = "类型";
            dgSite.Columns["NAME"].HeaderText = "名称";
            dgSite.Columns["PATHID"].HeaderText = "路径";
            dgSite.AutoResizeColumns();

            dgSite.CellContentClick += dataGridView1_CellContentClick;
            lbCount.Text = dtA.Rows.Count.ToString();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查点击的是否是IsSelected列
            if (e.ColumnIndex == dgSite.Columns["IsSelected"].Index)
            {
                for (int i = 0; i < dgSite.Rows.Count; i++)
                {
                    if (i != e.RowIndex)
                    {
                        // 取消其他行IsSelected列的勾选
                        dgSite.Rows[i].Cells["IsSelected"].Value = false;
                    }
                }
            }
        }

        private void txtParentID_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许输入数字、退格键和负号（仅在开头）
            if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
            {
                //不需要负号
                //if (e.KeyChar == '-' && textBox1.Text.Length == 0)
                //{
                //    return;
                //}
                e.Handled = true;
            }
        }

        private void txtPath_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许输入数字、退格键
            if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
            {
                e.Handled = true;
            }
        }

        private async void btnSearchPath_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtPath.Text))
            {
                MessageBox.Show("请输入上级节点ID");
                return;
            }
            txtName.Text = "";

            var dtA =await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.soureConnectionString, $@"SELECT ID,CLASSNAME,`NAME`,PATHID FROM dev_powersystemresource WHERE PATHID LIKE '\\\\{txtPath.Text}%' AND CLASSNAME IN( 'FactoryStation','Filiale' ) order by PATHID");
            if (dtA.Rows.Count == 0)
            {
                MessageBox.Show("没有查询到相关数据");
                return;
            }
            if (!dgSite.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                checkBoxColumn.HeaderText = "选中";
                checkBoxColumn.Name = "IsSelected";
                checkBoxColumn.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgSite.Columns.Add(checkBoxColumn);
            }

            // 为DataTable添加对应的列
            dtA.Columns.Add("IsSelected", typeof(bool));
            dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

            // 设置不允许新增行
            dgSite.AllowUserToAddRows = false;
            dgSite.AllowUserToDeleteRows = false; // 禁止删除行

            bindingSource1.DataSource = dtA;
            dgSite.DataSource = bindingSource1;

            //dataGridView1.DataSource = dtA;
            dgSite.Columns["ID"].HeaderText = "ID";
            dgSite.Columns["CLASSNAME"].HeaderText = "类型";
            dgSite.Columns["NAME"].HeaderText = "名称";
            dgSite.Columns["PATHID"].HeaderText = "路径";
            dgSite.AutoResizeColumns();

            //dataGridView1.CellContentClick += dataGridView1_CellContentClick;
            dgSite.CellContentClick -= dataGridView1_CellContentClick;

            lbCount.Text = dtA.Rows.Count.ToString();
        }


    }
}
